package com.jiangjun.fetch.scale;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.jiangjun.fetch.common.ImageFetch;
import com.jiangjun.fetch.common.WebContext;
import com.jiangjun.fetch.util.PathUtil;

public class ImageImpl implements ImageHelper {

	public String getPath4Weibo(String id,String parentId, String target_path, String type,
			int index, int flag, int width) {
		StringBuffer path = new StringBuffer();
		path.append(PathUtil.getPath4Weibo(id, parentId));
		if (flag == 0) {
			// 原图
			isFileDirOn(path.toString());
			path.append(id + "_" + index + "." + type);
		} else if (flag == 1) {
			// 缩略图
			path.append("m");
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(id + "." + type);
		} else if (flag == 2) {
			// 不同分辨率的大图
			path.append(width);
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(id + "_" + index + "." + type);
		} else if (flag == 3) {
			// 不同分辨率的webP图
			path.append(width);
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(id + "_" + index + "." + type);
		} else if (flag == 4) {
			// 缩略图的webp图
			path.append("m");
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(id + "." + type);
		}
		return path.toString();
	}

	@Override
	public String getPath(WebContext ctx, String type, int index, int flag,
			int width) {
		// TODO Auto-generated method stub
		StringBuffer path = new StringBuffer();
		path.append(PathUtil.getPath(ctx));

		if (flag == 0) {
			// 原图
			isFileDirOn(path.toString());
			path.append(ctx.getId() + "_" + index + "." + type);
		} else if (flag == 1) {
			// 缩略图
			path.append("m");
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(ctx.getId() + "." + type);
		} else if (flag == 2) {
			// 不同分辨率的大图
			path.append(width);
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(ctx.getId() + "_" + index + "." + type);
		} else if (flag == 3) {
			// 不同分辨率的webP图
			path.append(width);
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(ctx.getId() + "_" + index + "." + type);
		} else if (flag == 4) {
			// 缩略图的webp图
			path.append("m");
			path.append(File.separator);
			isFileDirOn(path.toString());
			path.append(ctx.getId() + "." + type);
		}
		return path.toString();
	}

	@Override
	public ImageFetch saveSourceImg(ImageFetch is, int index, WebContext ctx) {
		// TODO Auto-generated method stub
		String sourcePath = "";
		/**
		 * 1.抓取 2.获取type 3.获取路径
		 */
		HttpParams params = new BasicHttpParams();
		params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,
				false);
		// params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
		// HTTP.UTF_8);
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
				HttpVersion.HTTP_1_1);
		params.setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.BROWSER_COMPATIBILITY);
		params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
		params.setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
		params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
		params.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(is.getImg_src());
		httpGet.setParams(params);
		// 部分网站图片请求返回403
		httpGet.setHeader("Referer", ctx.getUrl());
		httpGet.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0");

		try {
			HttpResponse response = httpClient.execute(httpGet);
			System.out.println(response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				Header contentType = entity.getContentType();
				// 从content-type判断图片的格式
				String type = getImageTypeByContentType(contentType.getValue());
				byte[] result = EntityUtils.toByteArray(entity);
				if ("".equals(type)) {
					// 从byte[]中获取图片格式
					type = getImageTypeByByteArray(result);
					if ("".equals(type)) {
						type = getImageType(is.getImg_src());
						if ("".equals(type)) {
							type = "jpg";
						}
					}
				}

				sourcePath = getPath(ctx, type, index, 0, 0);
				saveFile(result, sourcePath);
				is.setImg_path(sourcePath);
				is.setType(type);
			}
		} catch (Exception e) {
			// TODO: handle exception
			is = null;
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return is;
	}

	@Override
	public String getImageType(String url) {
		// TODO Auto-generated method stub
		String type = "";
		url = url.toLowerCase();
		if (url.endsWith("png")) {
			type = "png";
		} else if (url.endsWith("jpeg")) {
			type = "jpeg";
		} else if (url.endsWith("jpg")) {
			type = "jpg";
		} else if (url.endsWith("gif")) {
			type = "gif";
		} else if (url.endsWith("ico")) {
			type = "ico";
		} else if (url.endsWith("bmp")) {
			type = "bmp";
		} else if (url.endsWith("wbmp")) {
			type = "wbmp";
		}
		return type;
	}

	/**
	 * 通过byte[]判断图片的格式
	 * 
	 * @return
	 */
	public String getImageTypeByByteArray(byte[] array) {
		String type = "";
		byte b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;
		/**
		 * 判断是否为gif
		 */
		if (array.length > 2) {
			b0 = array[0];
			b1 = array[1];
			b2 = array[2];
			if (b0 == 'G' && b1 == 'I' && b2 == 'F') {
				type = "gif";
			}
		}
		/**
		 * 判断是否为png
		 */
		if (array.length > 3) {
			b1 = array[1];
			b2 = array[2];
			b3 = array[3];
			if (b1 == 'P' && b2 == 'N' && b3 == 'G') {
				type = "png";
			}
		}

		/**
		 * 判断是否为jpg
		 */
		if (array.length > 9) {
			b6 = array[6];
			b7 = array[7];
			b8 = array[8];
			b9 = array[9];
			if (b6 == 'J' && b7 == 'F' && b8 == 'I' && b9 == 'F') {
				type = "jpeg";
			}
		}
		return type;
	}

	@Override
	public String getImageTypeByContentType(String contentType) {
		// TODO Auto-generated method stub
		if (contentType.indexOf(";") > -1) {
			contentType = contentType.split(";")[0];
		}
		String type = "";
		/* gif格式图片 */
		/**
		 * gif图片压缩的时候会生成多个文件
		 */
		if ("gif".equalsIgnoreCase(contentType)
				|| "image/gif".equalsIgnoreCase(contentType)) {
			type = "gif";
		}
		/* jpeg格式图片 */
		else if ("jpeg".equalsIgnoreCase(contentType)
				|| "image/jpeg".equalsIgnoreCase(contentType)) {
			type = "jpeg";
		}
		/* jpg格式图片 */
		else if ("jpg".equalsIgnoreCase(contentType)
				|| "image/jpg".equalsIgnoreCase(contentType)) {
			type = "jpg";
		}
		/* bmp格式图片 */
		else if ("bmp".equalsIgnoreCase(contentType)
				|| "image/bmp".equalsIgnoreCase(contentType)) {
			type = "bmp";
		} else if ("wbmp".equalsIgnoreCase(contentType)
				|| "image/wbmp".equalsIgnoreCase(contentType)) {
			type = "wbmp";
		}
		/* png格式图片 */
		else if ("png".equalsIgnoreCase(contentType)
				|| "image/png".equalsIgnoreCase(contentType)) {
			type = "png";
		}
		/* ico格式图片 */
		else if ("ico".equalsIgnoreCase(contentType)
				|| "image/ico".equalsIgnoreCase(contentType)) {
			type = "ico";
		}
		return type;
	}

	@Override
	public void saveFile(byte[] bytes, String path) {
		// TODO Auto-generated method stub
		InputStream in = null;
		FileOutputStream fs = null;
		try {
			in = new ByteArrayInputStream(bytes);
			fs = new FileOutputStream(path);
			byte[] buffer = new byte[1204];
			int byteread = 0;
			while ((byteread = in.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
			}
			fs.flush();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				if (null != fs)
					fs.close();
				if (null != in)
					in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	/**
	 * 判断目录是否创建，没有则创建
	 * 
	 * @param path
	 */
	public void isFileDirOn(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
	}
}
